

/**
 * 函数防抖 (只执行最后一次点击)
 * @param fn
 * @param delay
 * @returns {Function}
 * @constructor
 */
export const Debounce = (fn, t) => {
    const delay = t || 500;
    let timer;
    console.log(fn)
    console.log(typeof fn)
    return function () {
        const args = arguments;
        if(timer){
            clearTimeout(timer);
        }
        timer = setTimeout(() => {
            timer = null;
            fn.apply(this, args);
        }, delay);
    }
};
/**
 * 函数节流
 * @param fn
 * @param interval
 * @returns {Function}
 * @constructor
 */
export const Throttle = (fn, t) => {
    let last;
    let timer;
    const interval = t || 500;
    return function () {
        const args = arguments;
        const now = +new Date();
        if (last && now - last < interval) {
            clearTimeout(timer);
            timer = setTimeout(() => {
                last = now;
                fn.apply(this, args);
            }, interval);
        } else {
            last = now;
            fn.apply(this, args);
        }
    }
};

/**
 * @description: 将数字转成 k w 方式显示
 * @param {*} num
 * @return {*}
 */
export const formatNumber = (num) => {
    return num >= 1e3 && num < 1e4 ? (num / 1e3).toFixed(1) + 'k' : num >= 1e4 ? (num / 1e4).toFixed(1) + 'w' : num
}

/**
 * @description: 动态引入js
 * @param {*}
 * @return {*}
 */
export const injectScript = (src, attrs={}) => {
    const s = document.createElement('script');
    s.type = 'text/JavaScript';
    s.async = true;
    s.src = src;
    Object.getOwnPropertyNames(attrs).forEach(function (key){
        s[key] = attrs[key];
    })
    const t = document.getElementsByTagName('script')[0];
    t.parentNode.insertBefore(s, t);
}


export const isEmail = (s) => {
    return /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+((.[a-zA-Z0-9_-]{2,3}){1,2})$/.test(s)
}

export const isMobile = (s) => {
    return /^1[0-9]{10}$/.test(s)
}

export const isPhone = (s) => {
    return /^([0-9]{3,4}-)?[0-9]{7,8}$/.test(s)
}

export const isURL = (s) => {
    return /^http[s]?:\/\/.*/.test(s)
}

export const isString = (o) => {
    return Object.prototype.toString.call(o).slice(8, -1) === 'String'
}

export const isNumber = (o) => {
    return Object.prototype.toString.call(o).slice(8, -1) === 'Number'
}

export const isBoolean = (o) => {
    return Object.prototype.toString.call(o).slice(8, -1) === 'Boolean'
}

export const isFunction = (o) => {
    return Object.prototype.toString.call(o).slice(8, -1) === 'Function'
}

export const isNull = (o) => {
    return Object.prototype.toString.call(o).slice(8, -1) === 'Null'
}

export const isUndefined = (o) => {
    return Object.prototype.toString.call(o).slice(8, -1) === 'Undefined'
}

export const isObj = (o) => {
    return Object.prototype.toString.call(o).slice(8, -1) === 'Object'
}

export const isArray = (o) => {
    return Object.prototype.toString.call(o).slice(8, -1) === 'Array'
}

export const isDate = (o) => {
    return Object.prototype.toString.call(o).slice(8, -1) === 'Date'
}

export const isRegExp = (o) => {
    return Object.prototype.toString.call(o).slice(8, -1) === 'RegExp'
}

export const isError = (o) => {
    return Object.prototype.toString.call(o).slice(8, -1) === 'Error'
}

export const isSymbol = (o) => {
    return Object.prototype.toString.call(o).slice(8, -1) === 'Symbol'
}

export const isPromise = (o) => {
    return Object.prototype.toString.call(o).slice(8, -1) === 'Promise'
}

export const isSet = (o) => {  
    return Object.prototype.toString.call(o).slice(8, -1) === 'Set'
}

export const isWeiXin = () => {
    const ua = global.navigator.userAgent.toLowerCase();
    return ua.match(/microMessenger/i) === 'micromessenger'
}

export const isQQBrowser = () => {
    const ua = global.navigator.userAgent.toLowerCase();
    return !!ua.match(/mqqbrowser|qzone|qqbrowser|qbwebviewtype/i)
}

export const isSpider = () => {
    const ua = global.navigator.userAgent.toLowerCase();
    return /adsbot|googlebot|bingbot|msnbot|yandexbot|baidubot|robot|careerbot|seznambot|bot|baiduspider|jikespider|symantecspider|scannerlwebcrawler|crawler|360spider|sosospider|sogou web sprider|sogou orion spider/.test(ua)
}

export const isIos = () => {
    const u = navigator.userAgent;
    if (u.includes('Android') || u.includes('Linux')) {  // 安卓手机
        return false
    } else if (u.includes('iPhone')) {// 苹果手机
        return true
    } else if (u.includes('iPad')) {// iPad
        return false
    } else if (u.includes('Windows Phone')) {// winphone手机
        return false
    } else {
        return false
    }
}

/**
 * @description: 判断是不是移动端
 * @param {*}
 * @return {*}
 */
 export const isDeviceMobile = () => { 
    const ua = global.navigator.userAgent.toLowerCase();
    return /android|webos|iphone|ipod|balckberry/i.test(ua)
}

/**
 * @description: 判断是不是pc端
 * @param {*}
 * @return {*}
 */
export const isPC = () => {
    const userAgentInfo = navigator.userAgent;
    const Agents = ["Android", "iPhone", "SymbianOS", "Windows Phone", "iPad", "iPod"];
    let flag = true;
    for (let v = 0; v < Agents.length; v++) {
        if (userAgentInfo.indexOf(Agents[v]) > 0) {
            flag = false;
            break;
        }
    }
    return flag;
}

/**
 * @description: 清除html标签
 * @param {*}
 * @return {*}
 */
export const removehtmltag = (str) => {
    return str.replace(/<[^>]+>/g, '')
}
/**
 * @description: 获取url参数
 * @param {*}
 * @return {*}
 */
export const getQueryString = (name) => {
    const reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)', 'i');
    const search = window.location.search.split('?')[1] || '';
    const r = search.match(reg) || [];
    return r[2];
}

/**
 * @description: 根据url地址下载
 * @param {*}
 * @return {*}
 */
export const download = (url) => {
    const isChrome = navigator.userAgent.toLowerCase().includes('chrome');
    const isSafari = navigator.userAgent.toLowerCase().includes('safari');
    if (isChrome || isSafari) {
        const link = document.createElement('a');
        link.href = url;
        if (link.download !== undefined) {
            const fileName = url.substring(url.lastIndexOf('/') + 1, url.length);
            link.download = fileName;
        }
        if (document.createEvent) {
            const e = document.createEvent('MouseEvents');
            e.initEvent('click', true, true);
            link.dispatchEvent(e);
            return true;
        }
    }
    if (!url.includes('?')) {
        url += '?download';
    }
    window.open(url, '_self');
    return true;
}


/**
 * @description: el是否包含某个class
 * @param {*}
 * @return {*}
 */
export const hasClass = (el, className) => {
    const reg = new RegExp('(^|\\s)' + className + '(\\s|$)')
    return reg.test(el.className)
}

/**
 * @description: 添加class
 * @param {*}
 * @return {*}
 */
export const addClass = (el, className) => {
    if (hasClass(el, className)) {
        return
    }
    const newClass = el.className.split(' ')
    newClass.push(className)
    el.className = newClass.join(' ')
}

export const removeClass = (el, className) => {
    if (!hasClass(el, className)) {
        return
    }
    const reg = new RegExp('(^|\\s)' + className + '(\\s|$)', 'g')
    el.className = el.className.replace(reg, ' ')
}

/**
 * @description: 获取滚动坐标
 * @param {*}
 * @return {*}
 */
export const getScrollPosition = (el = window) => ({
    x: el.pageXOffset !== undefined ? el.pageXOffset : el.scrollLeft,
    y: el.pageYOffset !== undefined ? el.pageYOffset : el.scrollTop
});

/**
 * @description: 滚动到顶部
 * @param {*}
 * @return {*}
 */
export const scrollToTop = () => {
    const c = document.documentElement.scrollTop || document.body.scrollTop;
    if (c > 0) {
        window.requestAnimationFrame(scrollToTop);
        window.scrollTo(0, c - c / 8);
    }
}

/**
 * @description:el是否在视口范围内
 * @param {*}
 * @return {*}
 */
export const elementIsVisibleInViewport = (el, partiallyVisible = false) => {
    const { top, left, bottom, right } = el.getBoundingClientRect();
    const { innerHeight, innerWidth } = window;
    return partiallyVisible
        ? ((top > 0 && top < innerHeight) || (bottom > 0 && bottom < innerHeight)) &&
        ((left > 0 && left < innerWidth) || (right > 0 && right < innerWidth))
        : top >= 0 && left >= 0 && bottom <= innerHeight && right <= innerWidth;
}

/**
 * @description:洗牌算法随机
 * @param {*}
 * @return {*}
 */
export const shuffle = (arr) => {
    const result = [];
    let random;
    while (arr.length > 0) {
        random = Math.floor(Math.random() * arr.length);
        result.push(arr[random])
        arr.splice(random, 1)
    }
    return result;
}

/**
 * @description: 劫持粘贴板
 * @param {*}
 * @return {*}
 */
export const copyTextToClipboard = (value) => {
    const textArea = document.createElement("textarea");
    textArea.style.background = 'transparent';
    textArea.value = value;
    document.body.appendChild(textArea);
    textArea.select();
    try {
        // var successful = document.execCommand('copy');
    } catch (err) {
        console.log('Oops, unable to copy');
    }
    document.body.removeChild(textArea);
}

/**
 * @description: 判断类型集合
 * @param {*}
 * @return {*}
 */
export const checkStr = (str, type) => {
    switch (type) {
        case 'phone':   // 手机号码
            return /^1[3|4|5|6|7|8|9][0-9]{9}$/.test(str);
        case 'tel':     // 座机
            return /^(0\d{2,3}-\d{7,8})(-\d{1,4})?$/.test(str);
        case 'card':    // 身份证
            return /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/.test(str);
        case 'pwd':     // 密码以字母开头，长度在6~18之间，只能包含字母、数字和下划线
            return /^[a-zA-Z]\w{5,17}$/.test(str)
        case 'postal':  // 邮政编码
            return /[1-9]\d{5}(?!\d)/.test(str);
        case 'QQ':      // QQ号
            return /^[1-9][0-9]{4,9}$/.test(str);
        case 'email':   // 邮箱
            return /^[\w-]+(\.[\w-]+)*@[\w-]+(\.[\w-]+)+$/.test(str);
        case 'money':   // 金额(小数点2位)
            return /^\d*(?:\.\d{0,2})?$/.test(str);
        case 'URL':     // 网址
            return /(http|ftp|https):\/\/[\w\-_]+(\.[\w\-_]+)+([\w\-\\.,@?^=%&:/~\\+#]*[\w\-\\@?^=%&/~\\+#])?/.test(str)
        case 'IP':      // IP
            return /((?:(?:25[0-5]|2[0-4]\\d|[01]?\\d?\\d)\\.){3}(?:25[0-5]|2[0-4]\\d|[01]?\\d?\\d))/.test(str);
        case 'date':    // 日期时间
            return /^(\d{4})\\-(\d{2})\\-(\d{2}) (\d{2})(?:\\:\d{2}|:(\d{2}):(\d{2}))$/.test(str) || /^(\d{4})\\-(\d{2})\\-(\d{2})$/.test(str)
        case 'number':  // 数字
            return /^[0-9]$/.test(str);
        case 'english': // 英文
            return /^[a-zA-Z]+$/.test(str);
        case 'chinese': // 中文
            return /^[\\u4E00-\\u9FA5]+$/.test(str);
        case 'lower':   // 小写
            return /^[a-z]+$/.test(str);
        case 'upper':   // 大写
            return /^[A-Z]+$/.test(str);
        case 'HTML':    // HTML标记
            return /<("[^"]*"|'[^']*'|[^'">])*>/.test(str);
        default:
            return true;
    }
}